var vm = new Vue({
    el:"#app",
    data:{
        taskName:"",
        createUser:""
    },
    methods:{
        /**
         * 初始化bootstrapTable
         */
        initTable:function(){
            var _this = this;
            $('#tbTask').bootstrapTable($.extend(bootstrapTableOption,{
                url: g_comm.manager_url+'/speedTestTask/list',           //请求后台的URL（*）
                queryParams: _this.queryParams,               //传递参数（*）
                uniqueId: "id",                     //每一行的唯一标识，一般为主键列
                columns: [{
                    field: 'taskName',
                    title: '任务名称'
                },{
                    field: 'quotaStr',
                    title: '拨测指标'
                }, {
                    field: 'serverTypeStr',
                    title: '测速目标'
                },{
                    field: 'createUserStr',
                    title: '创建人'
                },{
                    field: '',
                    title: '操作',
                    formatter : function(value, row, index) {
                        return  '<div style="float:left;margin-right: 10px;width: 24px;height: 24px;" data-id="'+row.id+'" data-check-permission="business:task:update" onclick="vm.edit(this)">' +
                                    '<img src="static/img/dev/edit.png" title="编辑">' +
                                '</div>'+
                                '<div style="float:left;margin-right: 10px;width: 24px;height: 24px;" data-id="'+row.id+'" data-check-permission="business:task:delete" onclick="vm.delete(this)">' +
                                    '<img src="static/img/dev/delete.png" title="删除">' +
                                '</div>';
                    }
                }
                ]
            }));


        },
        /**
         * 查询参数
         * @param params
         */
        queryParams:function (params) {
            return {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
                limit: params.limit,   //页面大小
                offset: params.offset,  //页码
                taskName:this.taskName,
                createUser:this.createUser,
                serverType:$('#serverType').val()
            };
        },
        /**
         * 初始化自有服务器模板
         * */
        initOwnTpl:function (obj) {
            $.ajax({
                url: g_comm.manager_url+"/speedTestTask/ownResourceList",
                success: function(r){
                    // 渲染自有服务器模版
                    var data = r.data;
                    var getTpl = addAlertOwnTpl.innerHTML
                        ,view = document.getElementById('addAlertView');
                    layui.laytpl(getTpl).render(data, function(html){
                        view.innerHTML = html;
                        //多选下拉框
                        layui.formSelects.render('bbResource');
                        layui.formSelects.render('webResource');
                        layui.formSelects.render('videoResource');
                        layui.formSelects.render('fileResource');
                        if(obj){
                            for(var i=0; i<obj.length; i++){
                                if(obj[i].quota == 0){//宽带
                                    $('#addAlert .bbQuota').attr("checked", 'checked');
                                    $('#addAlert .bbQuota').attr("contentId", obj[i].contentId);
                                    if(obj[i].taskContentType != 1){
                                        layui.formSelects.undisabled('bbResource');
                                        layui.formSelects.value('bbResource', JSON.parse(obj[i].testResource));
                                    }else{//自动匹配
                                        $('#quotaType').removeAttr("disabled");
                                        $('#quotaType').attr("checked","checked");
                                    }
                                    layui.form.render('checkbox','quotaTypeDiv');
                                }//宽带--end

                                if(obj[i].quota == 1){//网页
                                    $('#addAlert .webQuota').attr("checked", 'checked');
                                    $('#addAlert .webQuota').attr("contentId", obj[i].contentId);
                                    layui.formSelects.undisabled('webResource');
                                    layui.formSelects.value('webResource', JSON.parse(obj[i].testResource));
                                }//网页--end

                                if(obj[i].quota == 2){//视频
                                    $('#addAlert .videoQuota').attr("checked", 'checked');
                                    $('#addAlert .videoQuota').attr("contentId", obj[i].contentId);
                                    layui.formSelects.undisabled('videoResource');
                                    layui.formSelects.value('videoResource', JSON.parse(obj[i].testResource));
                                }//视频--end

                                if(obj[i].quota == 3){//文件
                                    $('#addAlert .fileQuota').attr("checked", 'checked');
                                    $('#addAlert .fileQuota').attr("contentId", obj[i].contentId);
                                    layui.formSelects.undisabled('fileResource');
                                    layui.formSelects.value('fileResource', JSON.parse(obj[i].testResource));
                                }//文件--end
                            }

                        }//是否有值


                        //重新渲染表单
                        layui.form.render();
                        $('#addAlert .serverType input').next().remove();
                        //监听复选框
                        //宽带
                        layui.form.on('checkbox(bbQuota)', function(ckdata){
                            if(ckdata.elem.checked){
                                //默认自动匹配
                                $('#quotaType').removeAttr("disabled");
                                $('#quotaType').attr("checked","checked");
                            }else{
                                $('#quotaType').attr("disabled","disabled");
                                $('#quotaType').removeAttr("checked");
                                layui.formSelects.disabled('bbResource');
                            }
                            layui.form.render('checkbox','quotaTypeDiv');
                        });//宽带end

                        //网页
                        layui.form.on('checkbox(webQuota)', function(ckdata){
                            if(ckdata.elem.checked){
                                layui.formSelects.undisabled('webResource');
                            }else{
                                layui.formSelects.disabled('webResource');
                            }
                        });//网页end

                        //视频
                        layui.form.on('checkbox(videoQuota)', function(ckdata){
                            if(ckdata.elem.checked){
                                layui.formSelects.undisabled('videoResource');
                            }else{
                                layui.formSelects.disabled('videoResource');
                            }
                        });//视频end

                        //文件
                        layui.form.on('checkbox(fileQuota)', function(ckdata){
                            if(ckdata.elem.checked){
                                layui.formSelects.undisabled('fileResource');
                            }else{
                                layui.formSelects.disabled('fileResource');
                            }
                        });//文件end

                        //监听是否自动匹配
                        layui.form.on('switch(quotaType)', function(){
                            if(this.checked){
                                layui.formSelects.disabled('bbResource');
                            }else{
                                layui.formSelects.undisabled('bbResource');
                            }
                        });//监听是否自动匹配--END
                    });// 渲染自有服务器模版END
                }//success--end
            });
        },
        /**
         * 初始化第三方测速模板
         * */
        initThridPartTpl:function () {
            // 渲染第三方测速模板
            var data = { };
            var getTpl = addAlertThirdPartTpl.innerHTML
                ,view = document.getElementById('addAlertView');
            layui.laytpl(getTpl).render(data, function(html){
                view.innerHTML = html;
                //重新渲染表单
                layui.form.render();
                $('#addAlert .serverType input').next().remove();
                //监听复选框
                //宽带
                layui.form.on('checkbox(bbQuota)', function(ckdata){
                    if(ckdata.elem.checked){
                        //默认自动匹配
                        $('#addAlert .bbResource').removeAttr("disabled");
                    }else{
                        $('#addAlert .bbResource').attr("disabled","disabled");
                    }
                });//宽带end

                //网页
                layui.form.on('checkbox(webQuota)', function(ckdata){
                    if(ckdata.elem.checked){
                        $('#addAlert .webResource').removeAttr("disabled");
                    }else{
                        $('#addAlert .webResource').attr("disabled","disabled");
                    }
                });//网页end

                //视频
                layui.form.on('checkbox(videoQuota)', function(ckdata){
                    if(ckdata.elem.checked){
                        $('#addAlert .videoResource').removeAttr("disabled");
                    }else{
                        $('#addAlert .videoResource').attr("disabled","disabled");
                    }
                });//视频end

                //文件
                layui.form.on('checkbox(fileQuota)', function(ckdata){
                    if(ckdata.elem.checked){
                        $('#addAlert .fileResource').removeAttr("disabled");
                    }else{
                        $('#addAlert .fileResource').attr("disabled","disabled");
                    }
                });//文件end

            });// 渲染第三方测速模板END
        },
        /**
         * 初始化第三方测速模板
         * */
        initThridPartTpl2:function (obj) {
            // 渲染第三方测速模板
            var data = obj;
            var getTpl = editAlertThirdPartTpl.innerHTML
                ,view = document.getElementById('addAlertView');
            layui.laytpl(getTpl).render(data, function(html){
                view.innerHTML = html;
                //重新渲染表单
                layui.form.render();
                $('#addAlert .serverType input').next().remove();
                //监听复选框
                //宽带
                layui.form.on('checkbox(bbQuota)', function(ckdata){
                    if(ckdata.elem.checked){
                        //默认自动匹配
                        $('#addAlert .bbResource').removeAttr("disabled");
                    }else{
                        $('#addAlert .bbResource').attr("disabled","disabled");
                    }
                });//宽带end

                //网页
                layui.form.on('checkbox(webQuota)', function(ckdata){
                    if(ckdata.elem.checked){
                        $('#addAlert .webResource').removeAttr("disabled");
                    }else{
                        $('#addAlert .webResource').attr("disabled","disabled");
                    }
                });//网页end

                //视频
                layui.form.on('checkbox(videoQuota)', function(ckdata){
                    if(ckdata.elem.checked){
                        $('#addAlert .videoResource').removeAttr("disabled");
                    }else{
                        $('#addAlert .videoResource').attr("disabled","disabled");
                    }
                });//视频end

                //文件
                layui.form.on('checkbox(fileQuota)', function(ckdata){
                    if(ckdata.elem.checked){
                        $('#addAlert .fileResource').removeAttr("disabled");
                    }else{
                        $('#addAlert .fileResource').attr("disabled","disabled");
                    }
                });//文件end

            });// 渲染第三方测速模板END
        },
        /**
         * 第三方测速新增input
         * */
        addIconFn:function (obj) {
            if($(obj).parents('.layui-form-item').find('input[type="checkbox"]').is(':checked')
                && $(obj).parents('.input-item').find('input[type="text"]').val() != ''){
                //新增一个弹框，把原来的变为删除
                var itemStr = '<div class="input-item">' +$(obj).parents('.input-item').html()+'</div>';
                var $item = $(itemStr);
                $item.find('input[type="text"]').val('');
                $(obj).parents('.layui-form-item-right').append($item);

                //把之前的变为删除
                $(obj).html('<i class="layui-icon" style="color: red;">&#xe640;</i>');
                //更改之前事件属性
                $(obj).attr('onclick','vm.deleteIconFn(this)');

            }
        },
        /**
         * 第三方测速删除input
         * */
        deleteIconFn:function (obj) {
            $(obj).parents('.input-item').remove();
        },
        /**
         * */
        initAddAlert:function () {
            //切换自有服务器或者第三方测速
            $('#addAlert .serverType input').each(function(){
                var self = $(this),
                    label = self.next(),
                    label_text = self.parent().find('label').text();
                label.remove();
                self.iCheck({
                    radioClass: 'radio_sm-blue',
                    insert: label_text
                });
            });

            //监听切换
            $('#addAlert .serverType input').on('ifChecked', function(event){ //ifCreated 事件应该在插件初始化之前绑定
                var a = $("#addAlert .serverType input[name='serverType']:checked").val();
                if(a == 0){
                    vm.initOwnTpl();
                }else {
                    vm.initThridPartTpl();
                }
            });
        },
        /**
         * 新增
         * */
        add:function () {
            $('#addAlert .taskName').val('');
            $('#ownIcheck').iCheck('check');
            $('#thridIcheck').iCheck('uncheck');
            // 初始化
            vm.initOwnTpl();

            layer.open({
                type: 1,
                title: '新增',
                shade: false,
                area: ['600px', '600px'],
                content: $layui('#addAlert'),
                btn:['保存','取消'],
                yes:function () {
                    vm.saveForm();
                }
            });
        },
        /**
         * 保存
         * */
        saveForm:function (obj) {
            var params = {};
            //判断任务名称是否为空
            if($('#addAlert .taskName').val() == ''){
                layer.tips('任务名称不能为空', '#addAlert .taskName');
                return;
            }
            params.taskName = $('#addAlert .taskName').val();
            //判断选择的类型
            var serverType = $("#addAlert .serverType input[name='serverType']:checked").val();
            params.serverType = serverType;
            if(!$('#addAlert .bbQuota').prop('checked') && !$('#addAlert .webQuota').prop('checked')
                && !$('#addAlert .videoQuota').prop('checked') && !$('#addAlert .fileQuota').prop('checked')){
                layer.msg('测速内容不能为空');
                return;
            }
            var requestList = new Array();
            if(serverType == 0){//自有服务器

                if($('#addAlert .bbQuota').prop('checked')){
                    var bbPrama = {};
                    bbPrama.quota = 0;
                    if(layui.formSelects.value('bbResource', 'valStr') == '' && !$('#quotaType').prop('checked')){
                        layer.msg('宽带接入速率内容不能为空');
                        return;
                    }
                    if($('#quotaType').prop('checked')){
                        bbPrama.taskContentType = 1;
                    }else{
                        bbPrama.taskContentType = 0;
                    }
                    bbPrama.testResource =layui.formSelects.value('bbResource', 'valStr');
                    if($('#addAlert .bbQuota').attr('contentId') != undefined && $('#addAlert .bbQuota').attr('contentId') != ''){
                        bbPrama.contentId = $('#addAlert .bbQuota').attr('contentId');
                    }
                    requestList[requestList.length] = bbPrama;
                }//勾选了宽带测速--end

                if($('#addAlert .webQuota').prop('checked')){
                    var webPrama = {};
                    webPrama.quota = 1;
                    if(layui.formSelects.value('webResource', 'valStr') == ''){
                        layer.msg('网页体验测试内容不能为空');
                        return;
                    }
                    webPrama.taskContentType = 0;
                    webPrama.testResource =layui.formSelects.value('webResource', 'valStr');
                    if($('#addAlert .webQuota').attr('contentId') != undefined && $('#addAlert .webQuota').attr('contentId') != ''){
                        webPrama.contentId = $('#addAlert .webQuota').attr('contentId');
                    }
                    requestList[requestList.length] = webPrama;
                }//勾选了网页测速--end

                if($('#addAlert .videoQuota').prop('checked')){
                    var videoPrama = {};
                    videoPrama.quota = 2;
                    if(layui.formSelects.value('videoResource', 'valStr') == ''){
                        layer.msg('视频体验测试内容不能为空');
                        return;
                    }
                    videoPrama.taskContentType = 0;
                    videoPrama.testResource =layui.formSelects.value('videoResource', 'valStr');
                    if($('#addAlert .videoQuota').attr('contentId') != undefined && $('#addAlert .videoQuota').attr('contentId') != ''){
                        videoPrama.contentId = $('#addAlert .videoQuota').attr('contentId');
                    }
                    requestList[requestList.length] = videoPrama;
                }//勾选了视频体验测试--end

                if($('#addAlert .fileQuota').prop('checked')){
                    var filePrama = {};
                    filePrama.quota = 3;
                    if(layui.formSelects.value('fileResource', 'valStr') == ''){
                        layer.msg('文件下载速率内容不能为空');
                        return;
                    }
                    filePrama.taskContentType = 0;
                    filePrama.testResource =layui.formSelects.value('fileResource', 'valStr');
                    if($('#addAlert .fileQuota').attr('contentId') != undefined && $('#addAlert .fileQuota').attr('contentId') != ''){
                        filePrama.contentId = $('#addAlert .fileQuota').attr('contentId');
                    }
                    requestList[requestList.length] = filePrama;
                }//勾选了文件下载速率--end

                params.requestList = requestList;

            }
            else {//第三方测速
                if($('#addAlert .bbQuota').prop('checked')){
                    var bbPrama = {};
                    bbPrama.quota = 0;
                    //遍历内容，判断是否为空
                    var testResource ='';
                    $('#addAlert .bbResource').each(function (index,element) {
                        if($(element).val() != ''){
                            testResource += ','+$(element).val();
                        }
                    });
                    if(testResource == ''){
                        layer.msg('宽带接入速率内容不能为空');
                        return;
                    }
                    bbPrama.taskContentType = 0;
                    testResource=testResource.substr(1);
                    bbPrama.testResource =testResource;
                    if($('#addAlert .bbQuota').attr('contentId') != undefined && $('#addAlert .bbQuota').attr('contentId') != ''){
                        bbPrama.contentId = $('#addAlert .bbQuota').attr('contentId');
                    }
                    requestList[requestList.length] = bbPrama;
                }//勾选了宽带测速--end

                if($('#addAlert .webQuota').prop('checked')){
                    var webPrama = {};
                    webPrama.quota = 1;
                    //遍历内容，判断是否为空
                    var testResource ='';
                    $('#addAlert .webResource').each(function (index,element) {
                        if($(element).val() != ''){
                            testResource += ','+$(element).val();
                        }
                    });
                    if(testResource == ''){
                        layer.msg('网页体验测试内容不能为空');
                        return;
                    }
                    webPrama.taskContentType = 0;
                    testResource=testResource.substr(1);
                    webPrama.testResource =testResource;
                    if($('#addAlert .webQuota').attr('contentId') != undefined && $('#addAlert .webQuota').attr('contentId') != ''){
                        webPrama.contentId = $('#addAlert .webQuota').attr('contentId');
                    }
                    requestList[requestList.length] = webPrama;
                }//勾选了网页体验测试--end

                if($('#addAlert .videoQuota').prop('checked')){
                    var videoPrama = {};
                    videoPrama.quota = 2;
                    //遍历内容，判断是否为空
                    var testResource ='';
                    $('#addAlert .videoResource').each(function (index,element) {
                        if($(element).val() != ''){
                            testResource += ','+$(element).val();
                        }
                    });
                    if(testResource == ''){
                        layer.msg('视频体验测试内容不能为空');
                        return;
                    }
                    videoPrama.taskContentType = 0;
                    testResource=testResource.substr(1);
                    videoPrama.testResource =testResource;
                    if($('#addAlert .videoQuota').attr('contentId') != undefined && $('#addAlert .videoQuota').attr('contentId') != ''){
                        videoPrama.contentId = $('#addAlert .videoQuota').attr('contentId');
                    }
                    requestList[requestList.length] = videoPrama;
                }//勾选了视频体验测试--end

                if($('#addAlert .fileQuota').prop('checked')){
                    var filePrama = {};
                    filePrama.quota = 3;
                    //遍历内容，判断是否为空
                    var testResource ='';
                    $('#addAlert .fileResource').each(function (index,element) {
                        if($(element).val() != ''){
                            testResource += ','+$(element).val();
                        }
                    });
                    if(testResource == ''){
                        layer.msg('文件下载速率内容不能为空');
                        return;
                    }
                    filePrama.taskContentType = 0;
                    testResource=testResource.substr(1);
                    filePrama.testResource =testResource;
                    if($('#addAlert .fileQuota').attr('contentId') != undefined && $('#addAlert .fileQuota').attr('contentId') != ''){
                        filePrama.contentId = $('#addAlert .fileQuota').attr('contentId');
                    }
                    requestList[requestList.length] = filePrama;
                }//勾选了文件下载速率--end

                params.requestList = requestList;
            }
            var url;
            if(obj){
                var deleteList = new Array();
                params.taskId = obj.data.taskId;
                if(serverType != obj.data.serverType){
                    for (var i=0; i< obj.data.requestList.length; i++){
                        deleteList[i] = obj.data.requestList[i].contentId;
                    }
                }else{
                    if(!$('#addAlert .bbQuota').prop('checked') &&
                        $('#addAlert .bbQuota').attr('contentId') != undefined && $('#addAlert .bbQuota').attr('contentId') != ''){
                        deleteList[deleteList.length] = $('#addAlert .bbQuota').attr('contentId');
                    }
                    if(!$('#addAlert .webQuota').prop('checked') &&
                        $('#addAlert .webQuota').attr('contentId') != undefined && $('#addAlert .webQuota').attr('contentId') != ''){
                        deleteList[deleteList.length] = $('#addAlert .webQuota').attr('contentId');
                    }
                    if(!$('#addAlert .videoQuota').prop('checked') &&
                        $('#addAlert .videoQuota').attr('contentId') != undefined && $('#addAlert .videoQuota').attr('contentId') != ''){
                        deleteList[deleteList.length] = $('#addAlert .videoQuota').attr('contentId');
                    }
                    if(!$('#addAlert .fileQuota').prop('checked') &&
                        $('#addAlert .fileQuota').attr('contentId') != undefined && $('#addAlert .fileQuota').attr('contentId') != ''){
                        deleteList[deleteList.length] = $('#addAlert .fileQuota').attr('contentId');
                    }
                }
                params.deleteContentId = deleteList;
                url = g_comm.manager_url+"/speedTestTask/update";
            }else{
                url = g_comm.manager_url+"/speedTestTask/add";
            }
            console.log(params);
            $.ajax({
                type:"POST",
                url: url,
                traditional:true,
                data:JSON.stringify(params),
                contentType:"application/json",
                dataType: "json",
                success: function(r){
                    if(r.code == 0){//成功
                        layer.alert(r.msg,{icon: 1},function () {
                            vm.search();
                            layer.closeAll();
                        });
                    }else{
                        layer.alert(r.msg,{icon: 2},function () {
                            vm.search();
                            layer.closeAll();
                        });
                    }
                }//success--end
            });//AJAX--end
        },
        /**
         * 删除
         * */
        delete:function (obj) {
            var id = $(obj).attr('data-id');
            $.ajax({
                type:"DELETE",
                url: g_comm.manager_url+"/speedTestTask/delete?id="+id,
                success: function(r){
                    if(r.code == 0){//成功
                        layer.alert(r.msg,{icon: 1},function () {
                            vm.search();
                            layer.closeAll();
                        });
                    }else{
                        layer.alert(r.msg,{icon: 2},function () {
                            vm.search();
                            layer.closeAll();
                        });
                    }
                }//success--end
            });//AJAX--end

        },//detail---end
        /**
         * 编辑
         */
        edit:function(obj){
            var taskId = $(obj).attr('data-id');
            $.ajax({
                url: g_comm.manager_url+"/speedTestTask/queryByTaskId",
                data:{taskId:taskId},
                success: function(r){
                    console.log(r);
                    if(r.code == 0){
                        $('#addAlert .taskName').val(r.data.taskName);
                        if(r.data.serverType == 0){
                            $('#ownIcheck').iCheck('check');
                            $('#thridIcheck').iCheck('uncheck');
                            //初始化自有服务器
                            vm.initOwnTpl(r.data.requestList);
                        }else{
                            $('#thridIcheck').iCheck('check');
                            $('#ownIcheck').iCheck('uncheck');
                            //初始化第三方测速
                            vm.initThridPartTpl2(r.data.requestList);
                        }

                        layer.open({
                            type: 1,
                            title: '编辑',
                            shade: false,
                            area: ['600px', '600px'],
                            content: $layui('#addAlert'),
                            btn:['保存','取消'],
                            yes:function () {
                                vm.saveForm(r);
                            }
                        });


                    }

                }//success--end
            });//ajax---end
        },
        /**
         * 搜索
         */
        search:function () {
            $('#tbTask').bootstrapTable('refreshOptions',{pageNumber:1});
        },
    },
    mounted:function () {
        this.initTable();
        this.initAddAlert();
    }
});